package com.hruiworks.campusgroup.sse;

import com.hruiworks.campusgroup.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.concurrent.ScheduledExecutorService;

/**
 * 默认ManagedEmitterFactory
 */
@Slf4j
public class DefaultManagedEmitterFactory implements ManagedEmitterFactory{

    private final ScheduledExecutorService scheduler = SpringContextUtils.getBean(ScheduledExecutorService.class);



    @Override
    public ManagedEmitter getEmitter() {
        // 保持长连接
        SseEmitter sseEmitter = new SseEmitter(0L);
        return new ManagedEmitter(sseEmitter, scheduler);
    }

    @Override
    public ManagedEmitter getEmitter(ClearSseConnect clearSseConnect) {
        // 保持长连接
        SseEmitter sseEmitter = new SseEmitter(0L);
        sseEmitter.onCompletion(clearSseConnect::clear);
        sseEmitter.onTimeout(clearSseConnect::clear);
        sseEmitter.onError((ex)->{
            clearSseConnect.clear();
        });
        return new ManagedEmitter(sseEmitter, scheduler);
    }
}
